package com.imooc.framework.excel;

import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class HexColorExample {
    public static void main(String[] args) throws IOException {
        Workbook workbook = new XSSFWorkbook(); // 创建新的Excel工作簿
        Sheet sheet = workbook.createSheet("Sheet1"); // 创建一个工作表
        Row row = sheet.createRow(0); // 创建一行
        Cell cell = row.createCell(0); // 创建一个单元格

        String hexColor = "FF0000"; // 红色的十六进制值
        byte[] rgb = hexToRgb(hexColor); // 将十六进制颜色转换为RGB
        XSSFColor customColor = new XSSFColor(new java.awt.Color(255, 0, 0)); // 创建自定义颜色
//        customColor.setRGB(rgb);

//        //自定义cell颜色
//        HSSFPalette palette = workbook.getCustomPalette();
//        //这里的9是索引
//        palette.setColorAtIndex((short)9, (byte) r, (byte) g, (byte) b);


        cell.setCellValue("这是一个有颜色的单元格");
        XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle(); // 创建单元格样式
        style.setFillForegroundColor(customColor); // 设置前景填充颜色
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 设置填充模式
        cell.setCellStyle(style); // 应用样式到单元格

        FileOutputStream fileOut = new FileOutputStream("D:\\workbook12.xlsx");
        workbook.write(fileOut);
        fileOut.close();
        workbook.close();
    }

    private static byte[] hexToRgb(String hexColor) {
        if (hexColor.length() != 6) {
            throw new IllegalArgumentException("Invalid hex color: " + hexColor);
        }
        byte[] result = new byte[3];
        for (int i = 0; i < 3; i++) {
            int intValue = Integer.parseInt(hexColor.substring(i * 2, i * 2 + 2), 16);
            result[i] = (byte) intValue;
        }
        return result;
    }
}
